/*
 * Copyright 2009 Tran Nhut Trung.
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); 
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, 
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and 
 * limitations under the License.
 */
package org.eclipse.core.databinding.conversion.gwt;

import com.google.gwt.i18n.client.NumberFormat;

import org.eclipse.core.databinding.conversion.Converter;

public class NumberToStringConverter extends Converter{
  private final Class fromType;
  private NumberFormat numberFormat;
  private boolean fromTypeIsLong;
  private boolean fromTypeIsDecimalType;

  public NumberToStringConverter(Class fromType, NumberFormat numberFormat) {
    super(fromType, String.class);

    this.fromType = fromType;
    if (numberFormat == null){
      numberFormat = Converters.DEFAULT_NUMBER_FORMAT;
    }
    this.numberFormat = numberFormat;

    if ((Integer.class == fromType) || (fromType  == int.class)
        || (Long.class == fromType) || (fromType == long.class)) {
      fromTypeIsLong = true;
    } else if ((Float.class == fromType) || (fromType == float.class)
        || (Double.class == fromType) || (fromType == double.class)) {
      fromTypeIsDecimalType = true;
    } 
  }

  public Object convert(Object fromObject) {
    // Null is allowed when the type is not primitve.
    if (fromObject == null && !fromType.isPrimitive()) {
      return ""; //$NON-NLS-1$
    }

    Number number = (Number)fromObject;
    String result = null;
    if (fromTypeIsLong) {
      result = numberFormat.format(number.longValue()); 
    } else if (fromTypeIsDecimalType) {
      result = numberFormat.format(number.doubleValue());
    }
    
    return result;
  }

  public static NumberToStringConverter fromLong(NumberFormat numberFormat) {
    return new NumberToStringConverter(Long.class, numberFormat);
  }
  public static NumberToStringConverter fromInteger(NumberFormat numberFormat) {
    return new NumberToStringConverter(Integer.class, numberFormat);
  }
  public static NumberToStringConverter fromShort(NumberFormat numberFormat) {
    return new NumberToStringConverter(Short.class, numberFormat);
  }
  public static NumberToStringConverter fromByte(NumberFormat numberFormat) {
    return new NumberToStringConverter(Byte.class, numberFormat);
  }

  public static NumberToStringConverter fromDouble(NumberFormat numberFormat) {
    return new NumberToStringConverter(Double.class, numberFormat);
  }
  public static NumberToStringConverter fromFloat(NumberFormat numberFormat) {
    return new NumberToStringConverter(Float.class, numberFormat);
  }
}
